package http;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpServletResponse {

    private final OutputStream out;
    private final HttpServletRequest request;

    //头域参数集合
    private Map<String,String> headerMap = new HashMap<>();
    //状态码
    private int status;
    //响应信息
    private String msg;

    //定义servlet 数据输出流
    private CharArrayWriter caw = new CharArrayWriter();
    //资源流
    private  PrintWriter pw = new PrintWriter(caw);


    public HttpServletResponse(OutputStream out, HttpServletRequest request) {
        this.out = out;
        this.request = request;
    }

    public PrintWriter getWriter(){
        //将字符输出流保存到 内存中
        return pw;
    }

    public OutputStream getOutputStream() {
        return out;
    }

    //设值响应头域信息
    public void setHeader(String name, String value){
        headerMap.put(name, value);
    }

    //设置响应码
    public void setStatus(int status, String msg){
        this.status = status;
        this.msg = msg;
    }

    public void setContentType(String s) {
        setHeader("ContentType", "s");

    }

    //将数据推送给浏览器
    public void flushBuffer() throws IOException {
        //动态响应
        if (Tomcat.isDynamic(request)) {
            //设置默认 响应码
            if(status == 0){
                setStatus(200,"ok");
            }

            //头行
            out.write(String.format("Http/1.1 %d %s\n", status, msg).getBytes());

            //头域 map集合迭代
            for(Map.Entry<String, String> e : headerMap.entrySet()){
                out.write(String.format("%s: %s\n", e.getKey(), e.getValue()).getBytes());
            }

            //cookie迭代
            for (Cookie cookie : cookies){
                String s = cookie.getName()+"="+cookie.getValue();
                if(cookie.getMaxAge()!=null){
                    s += "; max-age=" + cookie.getMaxAge();
                }
                if(cookie.getMaxAge()!=null){
                    s += "; path=" + cookie.getPath();
                }
                out.write(String.format("Set-Cookie: %s\n", s).getBytes());
            }

            //空行
            out.write("\n".getBytes());
            //非响应重定向则输出响应体
            if(status < 300 || status > 399) {
                out.write(caw.toString().getBytes());
            }
        } else {
            out.write("HTTP/1.1 200 OK\n".getBytes());
            out.write("ContentType: text/html;charset=GBK\n".getBytes());
            //空行
            out.write("\n".getBytes());

            //构建请求资源路径的磁盘路径
            String path = Tomcat.webRootPath + request.getRequestURI();
            path = path.replaceAll("(.+)\\?(.*)", "$1");

            File file = new File(path);
            // 去取文件，并且向浏览器输出内容
            try {
                FileInputStream fis = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int count;
                while ((count = fis.read(bytes)) > 0) {
                    out.write(bytes, 0, count);
                }
            } catch (IOException E) {
                E.printStackTrace();
            }
        }
    }

    //添加cookie
    private List<Cookie> cookies = new ArrayList<>();
    public void addCookie(Cookie cookie){
        cookies.add(cookie);
    }

    //响应重定向
    public void sendRedirect(String path){
        //设置结果码
        setStatus(301,"Redirect");
        //设置跳转页面
        setHeader("Location", path);
    }

}
